#!/bin/bash

# RX教育平台 Kubernetes 部署脚本
# 使用方法: ./k8s-deploy.sh [操作]
# 操作: deploy|delete|status|logs

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查参数
if [ $# -lt 1 ]; then
    log_error "使用方法: $0 [操作]"
    log_info "操作: deploy|delete|status|logs|update"
    exit 1
fi

ACTION=$1

# 验证操作参数
if [[ ! "$ACTION" =~ ^(deploy|delete|status|logs|update)$ ]]; then
    log_error "无效的操作参数: $ACTION"
    log_info "支持的操作: deploy, delete, status, logs, update"
    exit 1
fi

# Kubernetes配置文件目录
K8S_DIR="./k8s"
NAMESPACE="rx-education"

# 检查kubectl
check_kubectl() {
    log_info "检查kubectl..."
    
    if ! command -v kubectl &> /dev/null; then
        log_error "kubectl 未安装或不在PATH中"
        exit 1
    fi
    
    # 检查集群连接
    if ! kubectl cluster-info &>/dev/null; then
        log_error "无法连接到Kubernetes集群"
        exit 1
    fi
    
    log_success "kubectl检查通过"
}

# 部署应用
deploy_app() {
    log_info "开始部署RX教育平台到Kubernetes..."
    
    # 创建命名空间
    log_info "创建命名空间..."
    kubectl apply -f $K8S_DIR/namespace.yaml
    
    # 部署存储
    log_info "部署存储配置..."
    kubectl apply -f $K8S_DIR/storage.yaml
    
    # 部署密钥
    log_info "部署密钥配置..."
    kubectl apply -f $K8S_DIR/secrets.yaml
    
    # 部署数据库
    log_info "部署数据库服务..."
    kubectl apply -f $K8S_DIR/database-deployment.yaml
    
    # 等待数据库就绪
    log_info "等待数据库服务就绪..."
    kubectl wait --for=condition=ready pod -l app=mysql -n $NAMESPACE --timeout=300s
    kubectl wait --for=condition=ready pod -l app=redis -n $NAMESPACE --timeout=300s
    
    # 部署后端
    log_info "部署后端服务..."
    kubectl apply -f $K8S_DIR/backend-deployment.yaml
    
    # 等待后端就绪
    log_info "等待后端服务就绪..."
    kubectl wait --for=condition=ready pod -l app=rx-backend -n $NAMESPACE --timeout=300s
    
    # 部署前端
    log_info "部署前端服务..."
    kubectl apply -f $K8S_DIR/frontend-deployment.yaml
    
    # 等待前端就绪
    log_info "等待前端服务就绪..."
    kubectl wait --for=condition=ready pod -l app=rx-admin-web -n $NAMESPACE --timeout=300s
    kubectl wait --for=condition=ready pod -l app=rx-student-web -n $NAMESPACE --timeout=300s
    kubectl wait --for=condition=ready pod -l app=rx-mobile-web -n $NAMESPACE --timeout=300s
    
    # 部署Ingress
    log_info "部署Ingress配置..."
    kubectl apply -f $K8S_DIR/ingress.yaml
    
    log_success "部署完成!"
    
    # 显示服务状态
    show_status
}

# 删除应用
delete_app() {
    log_info "开始删除RX教育平台..."
    
    # 删除Ingress
    kubectl delete -f $K8S_DIR/ingress.yaml --ignore-not-found=true
    
    # 删除前端
    kubectl delete -f $K8S_DIR/frontend-deployment.yaml --ignore-not-found=true
    
    # 删除后端
    kubectl delete -f $K8S_DIR/backend-deployment.yaml --ignore-not-found=true
    
    # 删除数据库
    kubectl delete -f $K8S_DIR/database-deployment.yaml --ignore-not-found=true
    
    # 删除密钥
    kubectl delete -f $K8S_DIR/secrets.yaml --ignore-not-found=true
    
    # 删除存储（可选，会删除数据）
    read -p "是否删除存储卷？这将删除所有数据 (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        kubectl delete -f $K8S_DIR/storage.yaml --ignore-not-found=true
        log_warning "存储卷已删除，所有数据已丢失"
    fi
    
    # 删除命名空间
    kubectl delete -f $K8S_DIR/namespace.yaml --ignore-not-found=true
    
    log_success "删除完成!"
}

# 更新应用
update_app() {
    log_info "开始更新RX教育平台..."
    
    # 重新部署后端
    kubectl rollout restart deployment/rx-backend -n $NAMESPACE
    
    # 重新部署前端
    kubectl rollout restart deployment/rx-admin-web -n $NAMESPACE
    kubectl rollout restart deployment/rx-student-web -n $NAMESPACE
    kubectl rollout restart deployment/rx-mobile-web -n $NAMESPACE
    
    # 等待更新完成
    kubectl rollout status deployment/rx-backend -n $NAMESPACE
    kubectl rollout status deployment/rx-admin-web -n $NAMESPACE
    kubectl rollout status deployment/rx-student-web -n $NAMESPACE
    kubectl rollout status deployment/rx-mobile-web -n $NAMESPACE
    
    log_success "更新完成!"
}

# 显示状态
show_status() {
    log_info "显示服务状态..."
    
    echo "\n=== 命名空间 ==="
    kubectl get namespace $NAMESPACE
    
    echo "\n=== Pods ==="
    kubectl get pods -n $NAMESPACE -o wide
    
    echo "\n=== Services ==="
    kubectl get services -n $NAMESPACE
    
    echo "\n=== Ingress ==="
    kubectl get ingress -n $NAMESPACE
    
    echo "\n=== 存储卷 ==="
    kubectl get pvc -n $NAMESPACE
    
    # 获取外部访问地址
    echo "\n=== 访问地址 ==="
    INGRESS_IP=$(kubectl get ingress rx-education-ingress -n $NAMESPACE -o jsonpath='{.status.loadBalancer.ingress[0].ip}' 2>/dev/null || echo "pending")
    if [ "$INGRESS_IP" != "pending" ] && [ -n "$INGRESS_IP" ]; then
        echo "管理后台: http://$INGRESS_IP (admin.rx-education.com)"
        echo "学生端: http://$INGRESS_IP (student.rx-education.com)"
        echo "移动端: http://$INGRESS_IP (mobile.rx-education.com)"
        echo "API: http://$INGRESS_IP (api.rx-education.com)"
    else
        echo "外部IP地址获取中，请稍后查看"
        echo "本地访问（端口转发）:"
        echo "kubectl port-forward svc/backend-service 3000:3000 -n $NAMESPACE"
        echo "kubectl port-forward svc/admin-web-service 3001:80 -n $NAMESPACE"
        echo "kubectl port-forward svc/student-web-service 3002:80 -n $NAMESPACE"
        echo "kubectl port-forward svc/mobile-web-service 3003:80 -n $NAMESPACE"
    fi
}

# 查看日志
view_logs() {
    log_info "查看服务日志..."
    
    echo "选择要查看日志的服务:"
    echo "1) 后端服务 (rx-backend)"
    echo "2) 管理后台 (rx-admin-web)"
    echo "3) 学生端 (rx-student-web)"
    echo "4) 移动端 (rx-mobile-web)"
    echo "5) MySQL数据库"
    echo "6) Redis缓存"
    
    read -p "请选择 (1-6): " choice
    
    case $choice in
        1)
            kubectl logs -f deployment/rx-backend -n $NAMESPACE
            ;;
        2)
            kubectl logs -f deployment/rx-admin-web -n $NAMESPACE
            ;;
        3)
            kubectl logs -f deployment/rx-student-web -n $NAMESPACE
            ;;
        4)
            kubectl logs -f deployment/rx-mobile-web -n $NAMESPACE
            ;;
        5)
            kubectl logs -f deployment/mysql -n $NAMESPACE
            ;;
        6)
            kubectl logs -f deployment/redis -n $NAMESPACE
            ;;
        *)
            log_error "无效选择"
            exit 1
            ;;
    esac
}

# 主逻辑
main() {
    log_info "开始执行 $ACTION 操作..."
    
    check_kubectl
    
    case $ACTION in
        "deploy")
            deploy_app
            ;;
        "delete")
            delete_app
            ;;
        "update")
            update_app
            ;;
        "status")
            show_status
            ;;
        "logs")
            view_logs
            ;;
    esac
    
    log_success "操作完成!"
}

# 执行主函数
main